package com.atguigu.spzx.service.impl;


import cn.hutool.core.date.DateUtil;
import com.atguigu.spzx.properties.MinioProperties;
import com.atguigu.spzx.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String fileUpload(MultipartFile multipartFile) {
        // 创建一个Minio的客户端对象
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                    .build();

            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            // 如果不存在，那么此时就创建一个新的桶
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {  // 如果存在打印信息
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists.");
            }
            String fileOriginalFilename = multipartFile.getOriginalFilename();
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-","");
            String filename = dateDir+"/"+uuid+fileOriginalFilename;
            //FileInputStream fis = new FileInputStream("D://R-C.jpg");
            InputStream inputStream = multipartFile.getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .stream(inputStream, inputStream.available(), -1)
                    .object(filename)
                    .build();
            minioClient.putObject(putObjectArgs);

            // 构建fileUrl
            String fileUrl = minioProperties.getEndpointUrl()+"/"+minioProperties.getBucketName()+"/"+filename;
            return fileUrl;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
